package org.k.vmmock.servlet;

import com.alibaba.fastjson.JSON;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.resource.loader.FileResourceLoader;
import org.k.vmmock.util.Conf;
import org.k.vmmock.util.FileUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Set;

/**
 * Created by hengxianwang on 16-10-29.
 */
public class MockVelocityServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private VelocityEngine engine;

    public MockVelocityServlet() {

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        Context context = new VelocityContext();
        String path = req.getServletPath();
        mock(context, path);
        final Template template =
                engine.getTemplate(path, "UTF-8");
        final StringWriter writer = new StringWriter();
        template.merge(context, new PrintWriter(writer));
        String content = writer.toString();

        /* 使用layout.vm
        context.put("screen_content", content);
        path = "page/layout/layout.vm";
        mock(context, path);
        final Template layoutTemplate =
                engine.getTemplate(path, "UTF-8");
        final StringWriter layoutWriter = new StringWriter();
        layoutTemplate.merge(context, new PrintWriter(layoutWriter));
        content = layoutWriter.toString();
        */
        resp.getWriter().write(content);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        engine = new VelocityEngine();
        engine.setProperty("resource.loader", "file");
        engine.setProperty("file.resource.loader.class", FileResourceLoader.class.getName());
        engine.setProperty("file.resource.loader.cache", Boolean.FALSE);
        engine.setProperty("file.resource.loader.path", Conf.getBasePath(false));
        engine.setProperty("input.encoding","UTF-8");
        engine.setProperty("output.encoding","UTF-8");
        engine.init();
        super.init();
    }




    public void mock(Context context, String path){
        if(path != null){
            path = path.replaceAll(Conf.get(Conf.PAGE_DIR),Conf.get(Conf.TEST_DIR)).replaceAll("vm","json");
        }
        try {
            String jsonStr = FileUtils.readFile2Str(Conf.getBasePath(false) + path);
            System.out.println("url:" + path + " ,find mock data:" + jsonStr);
            Map<String,Object> map = JSON.parseObject(jsonStr,Map.class);
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for(Map.Entry<String, Object> entry:entries){
                context.put(entry.getKey(),entry.getValue());
            }
        } catch (IOException e) {
            System.out.println("url:" + path + " hasn't mock data.");
        }
    }

}